// pages/meter_detail/detail.js
const app = getApp()
import _ from './../../utils/lodash.js';
import util from './../../utils/util.js';
import config from './../../utils/config.js';
let permissions = [];
if (app.globalData.userInfo) {
  permissions = app.globalData.userInfo.permissions
}
const find = _.find;


Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    concentrator_id:'',
    meter_number: '',
    concentrator_number: '',
    latitude: 42.92736760935551,
    longitude: 89.19229343394916,
    item: {},
    online_status: '',
    switch_valve_logs:[],
    meterHistory:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      meter_number:options.meter_number
    },function (){
      this.getInfo()
      this.getConcentrator()
      this.fetchSwitchLogs()
      this.fetchHistory();
    })
  },
  meterSwitch: function (e) {

    const that = this;
    console.log('that.data.item', that.data.item)
    wx.showModal({
      title: '提示',
      content: `确定要${Number(e.target.dataset.item)===1?'开阀':'关阀'}吗?`,
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');

          wx.request({
            url: `${config.prefix}/meter_valve_switch`,
            header: {
              Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'POST',
            data: {
              meter_ids: [that.data.meter_number],
              valve_status: Number(e.target.dataset.item)
            },
            success: function (res) {
              if (res.statusCode === 200) {
                wx.showToast({
                  title: '操作成功',
                  icon: 'success'
                })
                setTimeout(function () {
                  that.fetchSwitchLogs()
                }, 500)
              }
            }

          })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  fetchSwitchLogs: function () {
    const that = this;
    wx.request({
      url: `${config.prefix}/switch_valve_logs`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      data: {
        meter_number: this.data.meter_number,
        start_date: '2019-01-01',
        end_date: util.formatDate(new Date()),
        order_direction: 'desc',
        per_page: 5,
      },
      method: 'GET',
      success: function (res) {
        console.log('get res', res)

        if (res.statusCode === 200) {
          for (let i = 0; i < res.data.data.length; i++) {

            res.data.data[i].created_at = res.data.data[i].created_at.slice(5)
          }
          that.setData({
            switch_valve_logs: res.data.data,
          })

        }
        setTimeout(function () {
          wx.hideLoading()
        }, 500)
      }
    })
  },
  fetchHistory:function (){
    const that = this;
    wx.request({
      url: `${config.prefix}/meter_historical_data`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      data: {
        meter_id: this.data.meter_number,
        start_date: util.fun_date(-7),
        end_date: util.formatDate(new Date()),

      },
      method: 'GET',
      success: function (res) {
        console.log('get res', res)
        setTimeout(function () {
          wx.hideLoading()
        }, 500)
        if (res.statusCode === 200) {

          console.log('水表读数');
          that.setData({
            meterHistory: res.data.data.reverse()
          })
        }
      }
    })
  },
  bindtapDetail: function (e) {
    const ds = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/list_detail/detail?number=${this.data.concentrator_number}&id=${this.data.concentrator_id}`
    })
  },
  getConcentrator:function (){
    const that=this;
    wx.request({
      url: `${config.prefix}/concentrators`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'GET',
      data: {
        meter_number: this.data.meter_number,
      },
      success: function (res) {
        console.log('get res', res)
        if (res.statusCode === 200) {
          if( res.data.data.length===1){
            that.setData({
              concentrator_number:res.data.data[0].number,
              concentrator_id:res.data.data[0].id
            })
          }
        } else {
          util.converErrorCodeToMsg(res)
        }
      }


    })
  },
  getInfo: function () {
    const that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    wx.request({
      url: `${config.prefix}/meters/${this.data.meter_number}`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'GET',
      success: function (res) {
        console.log('get res', res)

        if (res.statusCode === 200) {
          const point = res.data.data;
          let val = point.signal_intensity;
          let signal_intensity_level = '';
          if (val !== '') {
            val = Number(val)
          }

          if (val == 99 || val == '') {
            signal_intensity_level = ''

          }
          if (0 <= val && val <= 10) {
            signal_intensity_level = 1
          } else if (10 < val && val <= 20) {
            signal_intensity_level = 2
          } else if (20 < val && val <= 30) {
            signal_intensity_level = 3
          } else if (30 < val && val < 32) {
            signal_intensity_level = 4
          } else {

          }
          point.signal_intensity_level = signal_intensity_level

          that.setData({
            item: point,
          }, function () {
          })

        } else {
          util.converErrorCodeToMsg(res)
        }
        setTimeout(function () {
          wx.hideLoading()
        }, 1000)
      }
    })


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})